package com.linxianqin.resilience4j.controller.circuitbreaker;

import com.linxianqin.resilience4j.domain.DemoBDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @version 1.0
 * @className: BackendBController
 * @description: TODO
 * @author: lxq
 * @date: 2021/8/16
 **/
@Slf4j
@RestController
@RequestMapping(value = "/circuitbreaker/backendC")
public class CircuitbreakerBackendCController {

    private final Map<String, DemoBDto> map = new HashMap<>();

    @PostConstruct
    private void init() {
        map.put("1", DemoBDto.of("1", "demoB id=1,测试断路器-backendC"));
        map.put("2", DemoBDto.of("2", "demoB id=2,测试断路器-backendC"));
        map.put("3", DemoBDto.of("3", "demoB id=3,测试断路器-backendC"));
        map.put("4", DemoBDto.of("4", "demoB id=4,测试断路器-backendC"));
        map.put("5", DemoBDto.of("5", "demoB id=5,测试断路器-backendC"));
        map.put("6", DemoBDto.of("6", "demoB id=6,测试断路器-backendC"));
    }

    @GetMapping("{aId}")
    public ResponseEntity<DemoBDto> getDemoBDto(@PathVariable String aId) throws InterruptedException {
        DemoBDto orDefault = this.map.getOrDefault(aId, new DemoBDto());
        return this.failRandomly(orDefault);
    }

    private ResponseEntity<DemoBDto> failRandomly(DemoBDto demoBDto){
        try{
            Thread.sleep(100);
        }catch (Exception e){
            e.printStackTrace();
        }
        int random = ThreadLocalRandom.current().nextInt(1, 4);
         if(random < 3){
            log.info("断路器模式|返回错误请求.");
            return ResponseEntity.badRequest().build();
        }
        log.info("断路器模式|请求成功.");
        return ResponseEntity.ok(demoBDto);
    }
}
